"use client"
import React, { useEffect, useState } from "react";
import { Card, Form, Input, Select } from "antd";
import baseInformationClass from "@/components/properties-panel-extension/components/index.module.css";

interface MyComponentProps {
    bpmnInstance: any,
}

interface DefaultOptionType {
    value: string;
    label: string;
}

// 按钮类型
type ButtonType =
    | 'agree' // 同意
    | 'reject' // 拒绝
    | 'return' // 驳回
    | 'revoke' // 撤销
    | 'delegate' // 指派
    | 'addSign' // 加签
    | 'reduceSign' // 减签
    | 'terminate' // 终止
    | 'intervene' // 干预

// 按钮配置
interface ButtonConfig {
    id: string
    name: string
    type: ButtonType
    sort: number
    enabled: boolean
}

// 流转类型
type FlowType = 'normal' | 'default' | 'button' | 'condition'

// 添加会签设置相关类型
interface MultiInstanceConfig {
    isSequential: boolean // 是否串行
    loopCardinality: string // 循环次数
    collection: string // 集合表达式
    elementVariable: string // 元素变量
    completionCondition: string // 完成条件
}

// 更新用户任务配置类型
interface UserTaskConfig {
    // ... 其他配置保持不变
    multiInstance?: MultiInstanceConfig // 会签配置
}

// 连线配置
interface SequenceConfig {
    flowType: FlowType
    buttonType?: ButtonType
    conditionExpression: string
}

// 连线配置组件
const ConnectionConfigurationView: React.FC<MyComponentProps> = (props: any) => {
    const [sequenceConfig, setSequenceConfig] = useState<SequenceConfig>({
        flowType: 'normal',
        buttonType: undefined,
        conditionExpression: '',
    })
    const { bpmnInstance } = props
    const { modeling, modeler, moddle, bpmnElement = {} } = bpmnInstance
    const [baseInfo, setBaseInfo] = useState<any>();
    useEffect(() => {
        if (bpmnElement?.businessObject) {
            // 判断流转类型
            if (bpmnElement.businessObject.get('flowable:isDefault')) {
                sequenceConfig.flowType = 'default'
            } else if (bpmnElement.businessObject.conditionExpression) {
                const expression = bpmnElement.businessObject.conditionExpression.body
                // 检查是否是按钮表达式
                const buttonMatch = expression?.match(/\${operationType == '(.+)'}/)
                if (buttonMatch) {
                    sequenceConfig.flowType = 'button'
                    sequenceConfig.buttonType = buttonMatch[1] as ButtonType
                } else {
                    sequenceConfig.flowType = 'condition'
                }
                sequenceConfig.conditionExpression = expression || ''
            } else {
                sequenceConfig.flowType = 'normal'
            }
        } else {
            // 重置配置
            setSequenceConfig(prevState => ({
                ...prevState,
                buttonType: undefined,
                conditionExpression: '',
                flowType: 'normal',
            }))
        }


        setBaseInfo({
            ...bpmnElement.businessObject,
        })
    }, [bpmnElement.businessObject]
    )
        ;
    // 更新参数
    useEffect(() => {
        handleSequenceChange()
    }, [sequenceConfig])

    // 处理流转类型变更
    const handleFlowTypeChange = (e: any) => {
        if (!bpmnElement || !modeler) return
        // 重置相关字段
        setSequenceConfig(prevState => ({
            ...prevState,
            buttonType: undefined,
            conditionExpression: '',
            flowType: e,
        }))
        if (e === 'default') {
            // 设置为默认流转路径
            modeling.updateProperties(bpmnElement, {
                'flowable:isDefault': true,
            })
        } else {
            // 移除默认流转标记
            modeling.updateProperties(bpmnElement, {
                'flowable:isDefault': undefined,
            })
        }
    }
    // 处理按钮类型变更
    const handleButtonTypeChange = (e: any) => {

        // 自动填充表达式
        setSequenceConfig(prevState => ({
            ...prevState,
            buttonType: e,
            conditionExpression: `\${operationType == '${e}'}`
        }))


    }
    const handleSequenceChange = (e?:  React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
        if(e?.target.value){
            setSequenceConfig(prevState => ({
                ...prevState,
                conditionExpression: e.target.value
            }))
        }
   
        if (!bpmnElement || !modeler) return
        // 只有在条件流转或按钮流转时才设置条件表达式
        if (sequenceConfig.flowType === 'condition' || sequenceConfig.flowType === 'button') {
            const conditionExpression = moddle.create('bpmn:FormalExpression', {
                body: sequenceConfig.conditionExpression,
            })
            modeling.updateProperties(bpmnElement, {
                conditionExpression,
            })
        } else {
            // 清除条件表达式
            modeling.updateProperties(bpmnElement, {
                conditionExpression: undefined,
            })
        }
    }
    const SequenceFlowTypeList: DefaultOptionType[] = [
        { label: '普通流转路径', value: 'normal' },
        { label: '默认流转路径', value: 'default' },
        { label: '内置按钮', value: 'button' },
        { label: '条件流转路径', value: 'condition' },
    ]
    // 按钮类型选项
    const buttonTypeOptions = [
        { label: '同意', value: 'agree' },
        { label: '拒绝', value: 'reject' },
        { label: '驳回', value: 'return' },
        { label: '撤销', value: 'revoke' },
        { label: '指派', value: 'delegate' },
        { label: '加签', value: 'addSign' },
        { label: '减签', value: 'reduceSign' },
        { label: '终止', value: 'terminate' },
        { label: '干预', value: 'intervene' },
    ]

    // 获取按钮类型的标签
    const getButtonTypeLabel = (type: ButtonType) => {
        return buttonTypeOptions.find((option) => option.value === type)?.label || ''
    }

    const assigneeTypeMap = SequenceFlowTypeList.reduce((acc, item) => {
        acc[item.value] = item.label;
        return acc;
    }, {} as Record<string, string>);
    return (
        <>
            <Card
                className={baseInformationClass.CardClass}
                title={`连线配置`}
                extra={null}>
                <Form>
                    <Form.Item
                        label="流转类型"
                        labelCol={{ span: 6 }}
                        wrapperCol={{ span: 18 }}>
                        <Select
                            value={[sequenceConfig?.flowType]}
                            style={{ width: '80%' }}
                            options={SequenceFlowTypeList}
                            onChange={(e) => handleFlowTypeChange(e)}
                        />
                    </Form.Item>
                    {sequenceConfig?.flowType == "button" && (<Form.Item
                        label="按钮类型"
                        labelCol={{ span: 6 }}
                        wrapperCol={{ span: 18 }}>
                        <Select
                            value={[sequenceConfig?.buttonType]}
                            defaultValue={[sequenceConfig?.buttonType]}
                            style={{ width: '80%' }}
                            options={buttonTypeOptions}
                            onChange={(e) => handleButtonTypeChange(e)}
                        />
                    </Form.Item>)

                    }
                    {sequenceConfig?.flowType == "button" || sequenceConfig?.flowType == "condition" ? (<Form.Item
                        label={`条件表达式`}
                        labelCol={{ span: 6 }}
                        wrapperCol={{ span: 18 }}>
                        <Input.TextArea
                            disabled={sequenceConfig.flowType === 'button'}
                            value={sequenceConfig?.conditionExpression}
                            onChange={(e) => handleSequenceChange(e)}
                        />
                    </Form.Item>) : (<></>)}

                </Form>
            </Card>


        </>

    );
}
    ;

export default ConnectionConfigurationView;
